package com.bridgeintelligent.tag.utils;
import com.bridgeintelligent.tag.constants.SharedErrors;
import com.wayneleo.quickstart.QuickException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.bridgeintelligent.tag.constants.PublicConstant.TXT;

/**
 * @description: 文件处理
 * @author: jensen
 * @date: created by 2020/4/30 2:55
 */
public class FileUtil {

    public static class FileFilter implements FilenameFilter {
        private String filterRule;

        public FileFilter( String filter ) {
            this.filterRule = filter;
        }

        @Override
        public boolean accept( File dir, String name ) {
            if ( name.lastIndexOf( '.' ) > 0 ) {
                // get last index for '.' char
                int lastIndex = name.lastIndexOf( '.' );
                // get extension
                String str = name.substring( lastIndex );
                // match path name extension
                if ( str.equals( this.filterRule ) ) {
                    return true;
                }
            }
            return false;
        }
    }

    /**
     * 根据规则获取文件名列表
     *
     * @param date     时间
     * @param filePath 路径
     * @param prefix   前缀
     * @return
     */
    public static List<String> fileRuleConvertList( String date, String filePath, String prefix ) {
        List<String> data = new ArrayList<>();
        try {
            // create new file
            File f = new File( filePath );
            // 文件文件名字过滤器
            FilenameFilter fileNameFilter = new FileFilter( ".ok" );
            File[] paths = f.listFiles( fileNameFilter );
            for ( File path : paths ) {
                // prints file and directory paths
                String name = path.getName();
                boolean b = name.endsWith( prefix + date + "_000.txt.ok" );
                if ( b ) {
                    String newPath = filePath + name.substring( 0, name.lastIndexOf( ".ok" ) );
                    data.add( newPath );
                }
            }
        }
        catch ( Exception e ) {
            // if any error occurs
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 读取txt文件
     *
     * @param txtPath
     * @return 返回读取到的内容
     */
    public static List<String> readTxt( String txtPath ) {
        List<String> data = new ArrayList<>();
        File file = new File( txtPath );
        if ( file.isFile() && file.exists() ) {
            try {
                BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( new FileInputStream( file ) ) );
                long curLineNo = 0;
                String text = null;
                while ( ( text = bufferedReader.readLine() ) != null ) {
                    // 第二行读取
                    if ( curLineNo > 0 ) {
                        data.add( text );
                    }
                    else {
                        curLineNo += 1;
                    }
                }
                bufferedReader.close();
                return data;
            }
            catch ( Exception e ) {
                e.printStackTrace();
            }
        }
        return data;
    }

    /**
     * 检查转换最新文件
     *
     * @param list
     * @param splitPattern
     * @return
     */
    public static List<String[]> checkData( List<String> list, String splitPattern ) {
        List<String[]> data = new ArrayList<>();
        if ( !CollectionUtils.isEmpty( list ) ) {
            for ( String str : list ) {
                String[] split = str.split( splitPattern );
                if ( split.length > 0 ) {
                    data.add( split );
                }
            }
        }
        return data;
    }
    /**
     * 判断是否是.csv 文件
     * @param fileName  文件名称
     * @return boolean
     */
    public static boolean getFileStatus(String fileName){
        boolean resutl = false;
        if(StringUtils.isNotEmpty(fileName)){
            int index = fileName.lastIndexOf(".");
            if(index > 0){
                String fileFormat = fileName.substring(index);

                if(TXT.equalsIgnoreCase(fileFormat)){
                    resutl = true;
                }
            }
        }
        return resutl;
    }
    /**
     * 判断目标文件路径下的文件是否存在
     * @param
     * @return
     */
    public static boolean pathFileIsExist(String pathFile){
        return new File(pathFile).exists();
    }
    /**
     * 如果目录不存在就创建目录
     *
     * @param path
     */
    public static void mkdirs(String path) {
        File f = new File(path);
        String fs = f.getParent();
        f = new File(fs);
        if (!f.exists()) {
            f.mkdirs();
        }
    }
    public static void mkdirss(String path) {
        File f = new File(path);
        if (!f.exists()) {
            f.mkdirs();
        }
    }
    /**
     * 创建文件
     *
     * @param path
     */
    public static boolean buildFile(String path) {
        File file = new File(path);
        if(!file.exists()){
            try {
                return file.createNewFile();
            } catch (IOException e) {
                throw QuickException.normal(SharedErrors.ERROR_401011.args(path),e);
            }
        }else return true;
    }
    /**
     * 文件是否存在
     *
     * @param path
     */
    public static boolean fileExist(String path) {
        File file = new File(path);
        return file.exists();
    }
    /**
     * 文件复制
     *
     * @param
     */
    public static void filecopy(String sourceFilePath,String destinationFilePath){
        // 复制文件
        try {
            Path sourcePath = new File(sourceFilePath).toPath();
            Path destinationPath = new File(destinationFilePath).toPath();
            Files.copy(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw QuickException.normal(SharedErrors.ERROR_401013.args(sourceFilePath),e);
        }
    }

    /**
     * 删除含有文件的目录
     *
     * @param
     */
    public static void del(File file){
        if(file.exists()&&file.isDirectory()){
            for(File f: Objects.requireNonNull(file.listFiles())){
                if(f.isDirectory()){
                    del(f);
                }else {
                    f.delete();
                }
            }
        }else{
            file.delete();
        }
        file.delete();
    }
    public static void main( String[] args ) {
//        String sfile = "D:\\waishu_20230213\\db2tbds\\20230418\\t_s_jk_gjj_jctq_gbase_20230418.csv";
//        String dfile = "D:\\waishu_20230213\\db2tbds\\20230418\\t_s_jk_gjj_jctq_inc_20230418.txt";
//        filecopy(sfile,dfile);
          del(new File("D:\\waishu_20230213\\xqsd\\20230515\\"));
//        String str = "今天知天{(3)}气不错，阳光挺{(10)}好的····',如何能把'{(3)},{(10)}........$FD........{12}";
//        String p2 = "\\{\\([^\\{\\}}]{1,}\\)\\}";// 确定{后面一定是(
//        Pattern p = Pattern.compile( p2 );
//        Matcher m = p.matcher( str );
//        while ( m.find() ) {
//            System.out.println( m.group() );
//
//        }
    }

}